package com.banggood.upms.converter;

import com.banggood.upms.bean.po.TreeTree;
import com.banggood.upms.bean.vo.TreeTreeVo;
import com.banggood.upms.common.component.CommonComponent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author XuChuangFeng
 * @date 2017/7/25
 */
@Component
public class TreeTreeConverter {

    @Autowired
    private CommonComponent component;

    /**
     * #1，将数据库中的树跟树的映射关系转换成Map集合
     * #2，判断前端传入的当前元素是否已经存在于数据库中（Map集合），若已存在则将这个元素从map中剔除，不存在则证明这个元素是要添加的，map中剩下的元素就是要删除的
     * @param vo 前端传入的，可以获取到最终调整之后的元素
     * @param preAdjustTreeTreeMappings DB中获取的，未调整之前的元素集合
     * @param treeTreeIdsForRemove 这次调整将要删除的upms_tree_Tree表中的主键
     * @param treeTreeListForInsert 这次调整将要添加的元素集合
     * @return
     */
    public void prepareAdjustElements(TreeTreeVo vo,
                                      List<TreeTree> preAdjustTreeTreeMappings, List<String> treeTreeIdsForRemove, List<TreeTree> treeTreeListForInsert) {
        Map<String, TreeTree> preAdjustTreeTreeMap = transferToMap(preAdjustTreeTreeMappings);
        for(String toTreeId : vo.getNewToTreeIds()) {
            // #1,若这个树的ID已经存在于调整前的集合中，证明这个元素已经是添加过的，不需要做调整
            if(preAdjustTreeTreeMap.containsKey(toTreeId)) {
                preAdjustTreeTreeMap.remove(toTreeId);
            } else {
                treeTreeListForInsert.add(preparePO(toTreeId, vo.getFromTreeId()));
            }
        }
        extractTreeTreeIdsForRemove(preAdjustTreeTreeMap, treeTreeIdsForRemove);
    }

    //将List转化为以toTreeId为Key，以TreeTree为value的Map
    public Map<String, TreeTree> transferToMap(List<TreeTree> pos) {
        Map<String, TreeTree> preAdjustTreeTreeMap = new HashMap<>();
        for(TreeTree po : pos) {
            preAdjustTreeTreeMap.put(po.getToTreeId(), po);
        }
        return preAdjustTreeTreeMap;
    }

    private void extractTreeTreeIdsForRemove(Map<String, TreeTree> preAdjustTreeTreeMap, List<String> treeTreeIdsForRemove) {
        for(String id : preAdjustTreeTreeMap.keySet()) {
            treeTreeIdsForRemove.add(preAdjustTreeTreeMap.get(id).getTreeTreeId());

        }
    }

    public List<TreeTree> transferToPersistentList(TreeTreeVo vo) {
        List<TreeTree> pos = new ArrayList<>();
        for(String id : vo.getNewToTreeIds()) {
            pos.add(preparePO(id, vo.getFromTreeId()));
        }
        return pos;
    }

    private TreeTree preparePO(String toTreeId, String fromTreeId) {
        TreeTree po = new TreeTree();
        po.setFromTreeId(fromTreeId);
        po.setToTreeId(toTreeId);
        po.setTreeTreeId(component.generateId());
        return po;
    }
}
